package dfs;

import java.util.ArrayList;
import java.util.List;

/**
 * 给定一个仅包含数字 2-9 的字符串，返回所有它能表示的字母组合。
 * 给出数字到字母的映射如下（与电话按键相同）。注意 1 不对应任何字母。
 * https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
 *
 * @author: luo
 * @email: luo@nyist.edu.cn
 * @date: 2021/1/23 16:20
 */
public class LetterCombinations {

    public static void main(String[] args) {
        // '0' 48 'a' 97
        /**
         * 97 98 99    100 101 102     103 104 105
         * 50           51              52
         */
        System.out.println(letterCombinations("7"));

    }

    public static List<String> letterCombinations(String digits) {
        char[] chars = digits.toCharArray();
        List<String> list = new ArrayList<>();
        backtracking(0, new char[chars.length], chars, list);
        return list;
    }

    private static void backtracking(int n, char[] chs, char[] chars, List<String> list) {
        if (n >= chars.length) {
            if (n == 0) {
                return;
            }
            list.add(new String(chs));
        } else {
            if (chars[n] == '9') {
                chs[n] = 'w';
                backtracking(++n, chs, chars, list);
                n--;
                chs[n] = 'x';
                backtracking(++n, chs, chars, list);
                n--;
                chs[n] = 'y';
                backtracking(++n, chs, chars, list);
                n--;
                chs[n] = 'z';
                backtracking(++n, chs, chars, list);
            } else if (chars[n] == '8') {
                chs[n] = 't';
                backtracking(++n, chs, chars, list);
                n--;
                chs[n] = 'u';
                backtracking(++n, chs, chars, list);
                n--;
                chs[n] = 'v';
                backtracking(++n, chs, chars, list);
            } else if (chars[n] == '7') {
                chs[n] = 'p';
                backtracking(++n, chs, chars, list);
                n--;
                chs[n] = 'q';
                backtracking(++n, chs, chars, list);
                n--;
                chs[n] = 'r';
                backtracking(++n, chs, chars, list);
                n--;
                chs[n] = 's';
                backtracking(++n, chs, chars, list);
            } else {
                char a = (char) (3 * (int) chars[n] - 53);
                chs[n] = a;
                backtracking(++n, chs, chars, list);
                n--;
                chs[n] = (char) ((int) a + 1);
                backtracking(++n, chs, chars, list);
                n--;
                chs[n] = (char) ((int) a + 2);
                backtracking(++n, chs, chars, list);
            }

        }
    }
}
